package game.ghostleg;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class OutSocket implements Runnable {
	private ArrayList<String> sockets;
	private ArrayList<Integer> ports;
	private int connection;
	private GhostLegView world;
	
	public OutSocket() {
	}
	
	public OutSocket(int numConnection, GhostLegView world) {
		this.sockets = new ArrayList<String> ();
		this.ports = new ArrayList<Integer> ();
		
		if ( 1 <= numConnection && numConnection <= 3 ) this.connection = numConnection;
		else System.out.printf("OutSocket creation failure : numConnection out of bound\n");
		this.world = world;
	}
	public boolean addConnection ( String host, int port ) {
		if ( sockets.size() > connection )
			return false;
		System.err.println("hihi");
		sockets.add(host);
		ports.add(port);
		this.world.outData.add(new SocketData(99,"connection established : "+host+String.format(" %d ", port)));
		System.err.println("123123");
		return true;
	}
	
	@Override
	public void run() {
		while ( this.world.time >= -1000 || this.world.time == -1 ) {
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				if ( world.outData.size() > 0 ) {
					//world.outLock.acquire();
					int i,n;
					n=sockets.size();
					Socket[] t_socket = new Socket[n];
					for(i=0;i<n;i++){
						try{
						t_socket[i] = new Socket(sockets.get(i),ports.get(i));
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							int portNum = ports.get(i) + 8;
							try {
								t_socket[i] = new Socket(sockets.get(i),portNum);
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
				try {
						
					ObjectOutputStream[] out = new ObjectOutputStream[n];
					for(i=0;i<n;i++)
					{
						
						out[i] = new ObjectOutputStream((t_socket[i]).getOutputStream());
					
						out[i].writeObject(new SocketData(99,world.outData.size()));
				
					}
					
				
					
					while(world.outData.size()>0)
					{
						for(i=0;i<n;i++)
							out[i].writeObject(world.outData.get(0));
						world.outData.remove(0);
						this.world.outDirty++;
					}
					//world.outLock.release();
					
					for(i=0;i<n;i++)
					{
						out[i].close();
						t_socket[i].close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		 
		}
		System.err.println("OutSocket bye");
	}
	
}
